<template>
  <div class="adInvoice-report-item table-gl-w">
    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :maxNum="6" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList" :showExport="true" fromLocation="结算报告" :exportInfo="exportInfo" :seachData="seachData" :checkedList="selectIds">
        <template #headerLeft>
          <a-space>
            <div class="flex-c">
              <a-select v-model="bindSalesman" value-key="id" allow-search allow-clear style="width: 140px" placeholder="选择运营">
                <a-option v-for="(item, index) in userList" :key="index" :value="item">{{ item.userName }}</a-option>
              </a-select>
              <a-button type="outline" size="medium" @click="onBatchBindSalesman">绑定运营</a-button>
            </div>
          </a-space>
        </template>
        <template #tableBody>
          <a-table
            class="table-singe-line show-border-table"
            ref="tableRef"
            row-key="id"
            :loading="tableLoading"
            :data="tableList"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :bordered="{ headerCell: true }"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="店铺" :width="160" fixed="left">
                <template #cell="{ record }">
                  <p>{{ getShopName(record) }}</p>
                </template>
              </a-table-column>
              <a-table-column title="站点" :width="60" data-index="marketplaceId">
                <template #cell="{ record }">
                  <span>{{ $extract(marketPlaceList[record.marketplaceId], 'code') }}</span>
                </template>
              </a-table-column>
              <a-table-column title="运营ID" :width="160" data-index="salesmanId" />
              <a-table-column title="运营" :width="150" data-index="salesmanName">
                <template #cell="{ record }">
                  <div v-if="!record.salesmanName">
                    <a-button size="mini" @click="onShowBindSalesmanDialog(record)">绑定</a-button>
                  </div>
                  <div v-else>
                    <a-button size="mini" @click="onShowBindSalesmanDialog(record)"> 重新绑定 </a-button>
                    {{ record.salesmanName }}
                  </div>
                </template>
              </a-table-column>
              <a-table-column title="发票" :width="130" data-index="costEventType">
                <template #cell="{ record }">
                  <span>{{ record.adInvoiceId.split('.')[2] }}</span>
                </template>
              </a-table-column>
              <a-table-column title="costEventType" :width="110" data-index="costEventType" />
              <a-table-column title="priceType" :width="80" data-index="priceType" />
              <a-table-column title="广告名称" :width="200" data-index="campaignName" />
              <a-table-column title="组合名字" :width="100" data-index="portfolioName" />
              <a-table-column title="programName" :width="200" data-index="programName" />
              <a-table-column title="costPerEventType" :width="130" data-index="costPerEventType" />
              <a-table-column title="costPerUnit" :width="100" data-index="costPerUnit" />
              <a-table-column title="costEventCount" :width="120" data-index="costEventCount" />
              <a-table-column title="campaignIdStr" :width="150" data-index="campaignIdStr" />
              <a-table-column title="币种" :width="50" data-index="costCurrency" />
              <a-table-column title="发票金额" :width="100" data-index="costAmt" :sortable="sortable" />
              <a-table-column title="开始时间" :width="100" data-index="fromDate" />
              <a-table-column title="结束时间" :width="100" data-index="toDate" />
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
    <!-- 绑定 -->
    <a-modal v-if="bindInfo.item" v-model:visible="bindSalesmanDialog" width="600px" title="绑定业务员" :footer="false" title-align="start" :mask-closable="false" ok-text="确认核销">
      <div class="bind-w">
        <h4> campaignId: {{ bindInfo.item.campaignIdStr }} , campaignName:{{ bindInfo.item.campaignName }}</h4>
        <a-alert :show-icon="false" :closable="false" type="success">以下人员来自该店铺运营人员和店长，确认绑定后，会更新本月及上月的所有明细，并且绑定到对应的广告活动中。</a-alert>
        <a-table class="table-normal-line" :scroll="{ y: 'calc(84vh - 240px)' }" :loading="bindInfo.showLoading" :data="bindInfo.shopUserList" size="mini" :bordered="false" :pagination="false">
          <template #columns>
            <a-table-column data-index="salesmanName" title="运营" />
            <a-table-column data-index="bind" title="绑定" align="right">
              <template #cell="{ record }">
                <a-button size="mini" type="outline" :disabled="bindInfo.submitLoading" @click="onBindSalesman(record)">绑定</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, ref, reactive } from 'vue'
  import { Message } from '@arco-design/web-vue'
  import { FilterTableItem, ExportInfo } from '@/types/components'
  import FilterTable from '@/components/TableFilter.vue'
  import useBaseDataStore from '@/store/modules/base-data'
  import { itemFind, batchUpdateCampaignSalesman, updateCampaignSalesman } from '@/api/finance/summaryReport'
  import { getStartAndEndTime } from '@/utils/timeFormat'
  import { marketPlaceList } from '@/utils/globalData'
  import { settlementItemSheet } from '@/utils/exportFiled'
  import { getShopMarketAndUserInfo } from '@/api/system'

  onMounted(async () => {
    setDefaultSearch()
    await getShopList()
    getUserList()
  })
  const emit = defineEmits(['toSearch'])
  const exportInfo: ExportInfo = {
    title: '结算报告明细',
    type: 'single',
    supportAll: true,
    tabName: '结算报告明细',
    fieldList: settlementItemSheet,
    supportTemplate: true,
    templateType: 'SETTLEMENT_ITEM_LIST',
    exportApi: 'exportSettlementItem',
    excelName: '结算明细报告',
  }
  const props = defineProps({
    searchVal: {
      type: Object,
      default: () => {},
    },
  })
  const searchVal = ref<any>({
    pageSize: 100,
    pageNum: 1,
  })
  const filterData = ref<any>({
    ...props.searchVal,
  })
  const tableLoading = ref(false)
  const useBaseData = useBaseDataStore()

  const tableList = ref<Array<any>>([])
  const userList = ref<Array<any>>([])
  const tableListMap = ref({})
  const selectIds = ref([])
  const tableRef = ref()
  const total = ref(0)
  const bindSalesman = ref<any>()
  const seachData = ref<any>({})
  const bindInfo = ref<any>({})
  const bindSalesmanDialog = ref(false)

  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
  }) as any
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any
  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'shopId',
      label: '店铺',
      value: ref(props.searchVal?.shopId ? props.searchVal.shopId.split(',') : null),
      type: 'select_multiple',
      width: 120,
      optionItems: [],
    },
    {
      key: 'invoiceId',
      label: '发票号',
      value: ref(props.searchVal.invoiceId),
      type: 'input_search',
      width: 180,
    },
    {
      key: 'noSalesman',
      label: '绑定业务员',
      value: ref(props.searchVal.invoiceId ? null : '1'),
      type: 'select',
      width: 120,
      optionItems: [{ label: '否', value: '1' }],
    },

    {
      key: 'salesmanId',
      label: '运营',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [],
    },
    {
      type: 'date_month',
      key: 'bookMonth',
      value: ref(),
      label: '核入月份',
      width: 120,
      attrs: {
        valueFormat: 'YYYYMM',
        placeholder: '核入月份',
      },
    },
    {
      type: 'keyword_date_range',
      key: 'searchTime',
      keyItems: [{ label: '发票结束日期', value: 'searchTime' }],
      keyWidth: '130',
      value: ref(props.searchVal.invoiceId ? null : getStartAndEndTime('this_month', 'YYYYMMDD')),
      placeholder: '请输入',
      label: '发票结束日期',
      width: 240,
      attrs: {
        valueFormat: 'YYYYMMDD',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
    {
      key: 'campaignName',
      label: '广告名',
      value: ref(),
      type: 'input_search',
      width: 180,
    },
    {
      key: 'portfolioName',
      label: '组合名',
      value: ref(),
      type: 'input_search',
      width: 180,
    },
  ])

  // 初始化查询
  function setDefaultSearch() {
    filterData.value = {
      shopId: props.searchVal.shopId,
      invoiceId: props.searchVal.invoiceId,
    }
    if (!props.searchVal.invoiceId) {
      filterData.value.dateType = 'toDate'
      filterData.value.begin = getStartAndEndTime('this_month', 'YYYYMMDD')?.[0]
      filterData.value.end = getStartAndEndTime('this_month', 'YYYYMMDD')?.[1]
      filterData.value.noSalesman = '1'
    }
    getTableList()
  }
  // 获取所有用户列表
  async function getUserList() {
    await useBaseData.getUserList()
    userList.value = useBaseData.userList
    filterItem.value[3].optionItems = useBaseData.userList.map((el: any) => {
      return {
        label: el.userName,
        value: el.id,
      }
    })
  }
  // 获取店铺
  async function getShopList() {
    await useBaseData.getShopList()
    filterItem.value[0].optionItems = useBaseData.shopList?.map((el: any) => {
      return {
        label: el.shopName,
        value: el.id,
      }
    })
  }
  // 绑定运营
  async function onBatchBindSalesman() {
    if (!selectIds.value.length) {
      Message.error('请选择明细！')
      return
    }
    if (!bindSalesman.value?.id) {
      Message.error('请选择业务员！')
      return
    }
    let campaignIdList: any = selectIds.value.map((id: string) => {
      let campaignIdStr = tableListMap.value[id]?.campaignIdStr
      return campaignIdStr
    })
    let param = {
      campaignIdList: campaignIdList,
      salesmanId: bindSalesman.value?.id,
      salesmanName: bindSalesman.value?.userName,
    }
    let rs = await batchUpdateCampaignSalesman(param)
    if (rs) {
      Message.success('修改成功')
      getTableList()
    }
  }

  // 显示店铺
  function getShopName(row: any) {
    return useBaseData.shopList?.find((item: any) => item.id === row.shopId)?.shopName || '未知'
  }
  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }

  // 通过条件查询列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData.value = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 绑定业务员
  async function onShowBindSalesmanDialog(item: any) {
    bindInfo.value.item = item
    bindSalesmanDialog.value = true
    bindInfo.value.showLoading = true

    const res: any = await getShopMarketAndUserInfo({
      id: item.shopId,
    })
    bindInfo.value.showLoading = false
    let shopUsers = res?.data?.shopUsers || []
    bindInfo.value.shopUserList = shopUsers.map((item: any) => {
      return {
        salesmanId: item.userId,
        salesmanName: item.userName,
        amt: 0,
      }
    })
  }
  // 绑定业务员
  async function onBindSalesman(salesman: any) {
    let param = {
      salesmanId: salesman.salesmanId,
      salesmanName: salesman.salesmanName,
      campaignId: bindInfo.value?.item?.campaignIdStr,
      adInvoiceId: bindInfo.value?.item?.adInvoiceId,
    }
    bindInfo.value.submitLoading = true
    let rs = await updateCampaignSalesman(param)
    bindInfo.value.submitLoading = false
    if (rs) {
      Message.success('更新成功!')
      getTableList()
      bindSalesmanDialog.value = false
    }
  }
  // 设置查询条件
  function setSearchval() {
    let _params: any = JSON.parse(JSON.stringify(filterData.value))
    _params.dateType = 'toDate'
    _params.begin = _params.startDate
    _params.end = _params.endDate
    _params.noSalesman = _params.noSalesman === '1' ? true : false

    delete _params.startDate
    delete _params.endDate
    delete _params.dataType

    return _params
  }

  // 获取商品列表
  async function getTableList() {
    tableList.value = []
    const _param = {
      pageSize: searchVal.value.pageSize,
      pageNum: searchVal.value.pageNum,
      ...setSearchval(),
    }
    // 非管理员未选择店铺时默认传所有店铺
    if (!_param.shopId && !_param.invoiceId) {
      Message.error('请选择店铺')
      return
      // let ids = useBaseData.shopList?.map((item: any) => item.id) || []
      // _param.shopId = ids.join(',')
    }

    tableLoading.value = true
    tableRef.value.selectAll(false)
    const res: any = await itemFind(_param)
    seachData.value = _param.param
    emit('toSearch', filterData.value)
    tableLoading.value = false
    tableList.value = res?.itemList || []
    total.value = res?.rows || 0
    tableListMap.value = {}
    tableList.value.forEach((item: any) => {
      tableListMap.value[item.id] = item
    })
  }
</script>

<style lang="less" scoped>
  .adInvoice-report-item {
    height: calc(100vh - @menuAndTabHeight);
  }
  .bind-w {
    h4 {
      font-weight: bold;
      margin-bottom: 10px;
    }
    .arco-alert {
      margin-bottom: 10px;
    }
  }
</style>
